package com.zzyl.serve.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.NursingPlan;
import com.zzyl.serve.domain.NursingProjectPlan;
import com.zzyl.serve.domain.dto.NursingPlanDto;
import com.zzyl.serve.domain.vo.NursingPlanVo;
import com.zzyl.serve.domain.vo.NursingProjectPlanVo;
import com.zzyl.serve.mapper.NursingPlanMapper;
import com.zzyl.serve.mapper.NursingProjectMapper;
import com.zzyl.serve.mapper.NursingProjectPlanMapper;
import com.zzyl.serve.service.INursingPlanService;
import com.zzyl.serve.service.INursingProjectPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 护理计划Service业务层处理
 *
 * @author Mr.Li
 * @date 2025-05-15
 */
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan> implements INursingPlanService {

    @Autowired
    private NursingPlanMapper nursingPlanMapper;

    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private INursingProjectPlanService nursingProjectPlanService;


    /**
     * 查询护理计划
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Long id) {
        NursingPlanVo vo = new NursingPlanVo();
        //1. 根据ID查询护理计划
        NursingPlan plan = this.getById(id);
        BeanUtils.copyProperties(plan, vo);

        //2. 查询关联的关系数据列表  select * from nuring_project_plan where plan_id=?
        List<NursingProjectPlan> nursingProjectPlans = nursingProjectPlanService.lambdaQuery()
                .eq(NursingProjectPlan::getPlanId, id).list();
        List<NursingProjectPlanVo> ppVoList = nursingProjectPlans.stream().map(pp -> {
            NursingProjectPlanVo ppVo = new NursingProjectPlanVo();
            ppVo.setId(String.valueOf(pp.getId()));
            ppVo.setPlanId(String.valueOf(pp.getPlanId()));
            ppVo.setProjectId(String.valueOf(pp.getProjectId()));
            ppVo.setExecuteTime(String.valueOf(pp.getExecuteTime()));
            ppVo.setExecuteFrequency(String.valueOf(pp.getExecuteFrequency()));
            ppVo.setExecuteCycle(String.valueOf(pp.getExecuteCycle()));
            return ppVo;
        }).collect(Collectors.toList());

        //3. 组装数据
        vo.setProjectPlans(ppVoList);
        return vo;
    }

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 新增护理计划
     *
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertNursingPlan(NursingPlanDto dto) {
        NursingPlan plan = new NursingPlan();
        //copyProperties的作用：复制源对象的属性给目标对象
        BeanUtils.copyProperties(dto, plan);

        //1. 保存护理计划
        boolean resultPlan = this.save(plan);
        if (!resultPlan) {
            throw new BaseException("保存护理计划失败");
        }

        //2. 批量保存护理计划和护理项目的关系数据
        List<NursingProjectPlan> projectPlanList = dto.getProjectPlans();
        projectPlanList.forEach(x -> {
            x.setPlanId(plan.getId());//设置护理计划主键id
        });
        boolean resultPP = nursingProjectPlanService.saveBatch(projectPlanList);
        if (!resultPP) {
            throw new BaseException("保存护理计划和护理项目的关系数据失败");
        }

        return 1;
    }


    /**
     * 修改护理计划
     *
     * @param dto 护理计划
     * @return 结果
     */
    @Transactional
    @Override
    public int updateNursingPlan(NursingPlanDto dto) {
        //删除缓存
        removeCache();
        //拷贝对象
        NursingPlan plan = new NursingPlan();
        BeanUtils.copyProperties(dto, plan);

        List<NursingProjectPlan> projectPlans = dto.getProjectPlans();

        //如果护理项目列表非空，删除旧关系，批量保存新关系
        if (CollectionUtils.isNotEmpty(projectPlans)) {
            nursingProjectPlanMapper.delete(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId, plan.getId()));
            projectPlans.forEach(x -> {
                x.setPlanId(plan.getId());
                x.setCreateTime(LocalDateTime.now());
            });
            nursingProjectPlanMapper.batchInsert(projectPlans);
        }

        //不管护理项目列表是否为空，都更新护理计划
        return this.updateById(plan) ? 1 : 0;
    }

    /**
     * 批量删除护理计划
     *
     * @param ids 需要删除的护理计划主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteNursingPlanByIds(Long[] ids) {
        //删除缓存
        removeCache();
        //删除关联数据
        for (Long id : ids) {
            nursingProjectPlanMapper.delete(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId, id));
        }

        //删除护理计划数据
        return this.removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 查询全部护理计划列表
     *
     * @return
     */
    @Override
    public List<NursingPlanVo> getAll() {
        // 1.查询缓存中是否存在
        List<String> rangeJSON = redisTemplate.opsForList().range(CacheConstants.NURSING_PLAN_LIST_KEY, 0, -1);

        // 2.查询如果存在返回前端数据
        List<NursingPlanVo> voList = null;
        if (CollUtil.isNotEmpty(rangeJSON)) {
            // 2.1 集合转对象
            voList = rangeJSON.stream().map(x -> JSON.parseObject(x, NursingPlanVo.class)).collect(Collectors.toList());
        }

        // 3.不存在查询数据库存入缓存
        if (CollUtil.isEmpty(voList)) {
            // 3.1查询数据库
            List<NursingPlan> nursingPlanList = this.lambdaQuery().select(NursingPlan::getPlanName, NursingPlan::getId).eq(NursingPlan::getStatus, 1).list();
            voList = nursingPlanList.stream().map(x -> {
                NursingPlanVo vo = new NursingPlanVo();
                vo.setLabel(x.getPlanName());
                vo.setValue(x.getId().intValue());
                // 3.2缓存数据
                redisTemplate.opsForList().leftPush(CacheConstants.NURSING_PLAN_LIST_KEY, JSON.toJSONString(vo));
                return vo;
            }).collect(Collectors.toList());

        }

        // 4.返回前端数据
        return voList;
    }

    /**
     * 删除缓存数据
     */
    private void removeCache() {
        // 1.查询缓存中是否存在
        List<String> rangeJSON = redisTemplate.opsForList().range(CacheConstants.NURSING_PLAN_LIST_KEY, 0, -1);
        // 2.查询如果存在删除
        if (CollUtil.isNotEmpty(rangeJSON)) {
            redisTemplate.delete(CacheConstants.NURSING_PLAN_LIST_KEY);
        }
    }
}